package com.pay.sdk.aidl;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.pay.sdk.interfaces.GetPayStatusListener;

/**
 * Created by Joe on 2017/4/6 0006 17:59.
 */

public class AidlUtils {
    private Activity mActivity;
    private String payResult;

    public AidlUtils(Activity activity, GetPayStatusListener payStatusListener) {
        mActivity = activity;
        mGetPayStatusListener = payStatusListener;

    }

    private static final String TAG = "AIDLUtils";
    private ForRemoteAidlInterface mService;
    private GetPayStatusListener mGetPayStatusListener;

    private void Log(String str) {
        Log.d(TAG, "------ " + str + "------");
    }

    private ForClientAidlInterface mCallback = new ForClientAidlInterface.Stub() {
        @Override
        public void getPayAction(String payStatus) throws RemoteException {
            payResult = payStatus;
            Log(payResult);
            if (mGetPayStatusListener != null) {
                mGetPayStatusListener.onPayStatus(payResult);
            }
        }
    };

    public void getPayStatus() {
        if (mService != null) {
            try {
                mService.invokCallBack();
            } catch (RemoteException e) {
                e.printStackTrace();
                Log("RemoteException Error invokCallBack");
            }
        }else {
            Log("Service Error null");
        }
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            Log("onServiceConnected ");
            mService = ForRemoteAidlInterface.Stub.asInterface(service);
            try {
                mService.registerPayCall(mCallback);
            } catch (RemoteException e) {
                Log("RemoteException Error");
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            Log("disconnect service");
            mService = null;
        }
    };

    public boolean bindAidlService() {
        try {
            Intent intent = new Intent("PayAIDL.QueryStatus");
            intent.setPackage("com.jtpay.wallet");
            boolean bindResult = mActivity.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
            return bindResult;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
